package com.zyf.controller;

import com.zyf.pojo.News;
import com.zyf.pojo.Userinfo;
import com.zyf.service.NewsService;
import com.zyf.service.UserInfoService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class MyController {

    @Resource
    UserInfoService service;

    @Resource
    NewsService newsService;

    @PostMapping("/login")
    public String login(Userinfo userinfo, Model model, HttpSession session){
        Userinfo login = service.login(userinfo);
        if (login==null){
            model.addAttribute("message","用户名或密码错误");
            return "../index";
        }
        session.setAttribute("session",login);
        return "redirect:/news/findAll";
    }

    @GetMapping("/user/toAdd")
    public String findOne(Integer userid,Model model){
        System.out.println(userid);
        Userinfo one = service.findOne(userid);
        System.out.println(one);
        model.addAttribute("user",one);
        return "add";
    }

    @GetMapping("/news/findAll")
    public String findAll(Model model){
        List<News> all = newsService.findAll();
        model.addAttribute("news",all);
        return "main";
    }

    @PostMapping("/news/add")
    private String add(News news,Model model){
        int add = newsService.add(news);
        if(add<=0){
            model.addAttribute("message","添加失败请注意规范");
            return "add";
        }
        return "redirect:/news/findAll";
    }
}
